﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace KPIBalanceScoreCard
{
    public partial class Hierarchy : System.Web.UI.MasterPage
    {
        public TreeNode currentNode = new TreeNode();
        private String displayMessage = "";

        public String message
        {
            get
            {
                String tempMessage = displayMessage;
                displayMessage = "";
                return tempMessage;
            }
            set
            {
                displayMessage = "<script> alert('" + value + "') </script>";
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            // Session[ApplicationConstants.LOGIN_PK.ToString()] = "R1201ADEL"; //"R010"; //  "R2403";// "R4749";// 

            String currLoginId = Session[ApplicationConstants.LOGIN_PK.ToString()].ToString();
            //String currRole = new HierarchyDatasetTableAdapters.EmployeeRoleAdapter().GetEmployeeRole(currLoginId).Rows[0][0].ToString();



            if (!IsPostBack)
            {
                String currentYear = new HierarchyDatasetTableAdapters.MaxDateTableAdapter().GetMaxYear().Rows[0][0].ToString();
                String currentMonth = new HierarchyDatasetTableAdapters.MaxDateTableAdapter().GetMaxMonth().Rows[0][0].ToString();

                Session[ApplicationConstants.CHOOSEN_YEAR.ToString()] = currentYear;
                Session[ApplicationConstants.CHOOSEN_MONTH.ToString()] = currentMonth;

                // hierarchyTreeView.Nodes.Add(initializeTreeDiscarded(currLoginId));                
                Session[ApplicationConstants.TREE_STRUCTURE.ToString()] = null;
                hierarchyTreeView.Nodes.Clear();
                bool isAdmin = Boolean.Parse(Session[ApplicationConstants.IS_ADMIN.ToString()] == null ? "false" : Session[ApplicationConstants.IS_ADMIN.ToString()].ToString());
                if (isAdmin)
                {
                    HierarchyDataset.AdminDataTable adt = (HierarchyDataset.AdminDataTable)  new HierarchyDatasetTableAdapters.AdminTableAdapter().GetData();
                    foreach (HierarchyDataset.AdminRow row in adt.Rows)
                    {
                        TreeNode tn = initializeTree(row.EmployeeUserRef);

                        if (!tn.Value.Equals(Roles.PROHIBITED.ToString()))
                        {
                            hierarchyTreeView.Nodes.Add(tn);
                        }
                    }

                }
                else
                {

                    hierarchyTreeView.Nodes.Add(initializeTree(currLoginId));
                } 
                hierarchyTreeView.ExpandAll();
            }
            else
            {
                if (!Session[ApplicationConstants.CHOOSEN_MONTH.ToString()].Equals(Request["ctl00$ContentPlaceHolder1$monthDropDown"]) || !Session[ApplicationConstants.CHOOSEN_YEAR.ToString()].Equals(Request["ctl00$ContentPlaceHolder1$yearDropDown"]))
                {
                    Session[ApplicationConstants.CHOOSEN_MONTH.ToString()] = Request["ctl00$ContentPlaceHolder1$monthDropDown"];
                    Session[ApplicationConstants.CHOOSEN_YEAR.ToString()] = Request["ctl00$ContentPlaceHolder1$yearDropDown"];

                    refreshTree_Click(sender, e);
                    
                }

                currentNode = (TreeNode)Session[ApplicationConstants.CURRENT_NODE.ToString()];
            }
        }

        private TreeNode makeDBDAreaMgr(string currLoginId)
        {
            throw new NotImplementedException();
        }

        private TreeNode initializeTree(string currLoginId)
        {
            // Adding Organization Parent Name
            TreeNode firstLevelNode = null;
            TreeNode secondLevelNode = null;
            TreeNode rootNode = new TreeNode("DSD", "");

                String valuePrefix = "";

                HierarchyDataset.AreaNBranchDataTable areaNBrachDt = new HierarchyDatasetTableAdapters.AreaNBranchTableAdapter().GetAreaNBranch(currLoginId, Double.Parse(Session[ApplicationConstants.CHOOSEN_YEAR.ToString()].ToString()), Double.Parse(Session[ApplicationConstants.CHOOSEN_MONTH.ToString()].ToString()));

                String currentRole = "";
                try
                {
                    currentRole = new HierarchyDatasetTableAdapters.EmployeeRoleAdapter().GetEmployeeRole(currLoginId.Trim(), Double.Parse(Session[ApplicationConstants.CHOOSEN_YEAR.ToString()].ToString()), Double.Parse(Session[ApplicationConstants.CHOOSEN_MONTH.ToString()].ToString())).Rows[0][0].ToString();

                }
                catch (Exception e1)
                {
                    return new TreeNode("No Data Available", Roles.PROHIBITED.ToString());
                }
                currentRole = currentRole.Trim();

                // Adding objects to session
                Session[ApplicationConstants.LOGIN_NAME.ToString()] = new HierarchyDatasetTableAdapters.GetEmpNameTableAdapter().GetEmployeeName(currLoginId).ToString();

                Session[ApplicationConstants.CURRENT_ROLE.ToString()] = currentRole;


                firstLevelNode = new TreeNode();
                secondLevelNode = new TreeNode();

                firstLevelNode.Text = areaNBrachDt.Rows[0][HierarchyDSD.treeSequence[0][0]].ToString();// +"_AreaMgr";
                firstLevelNode.Value = valuePrefix + ApplicationStrings.ROLE_PREFIX + Roles.AreaMgr.ToString() + Roles.PROHIBITED;

                valuePrefix += areaNBrachDt.Rows[0][HierarchyDSD.treeSequence[0][0]].ToString() + "@@!!";

                if (currentRole.Trim().Equals(HierarchyDSD.treeSequence[0][1]))
                {
                    firstLevelNode.Text = firstLevelNode.Text;// +"_" + currentRole;
                    firstLevelNode.Value = valuePrefix + ApplicationStrings.ROLE_PREFIX + currentRole;

                    secondLevelNode.Text = Session[ApplicationConstants.LOGIN_NAME.ToString()].ToString();
                    secondLevelNode.Value = valuePrefix + ApplicationStrings.EMP_NAME_PREFIX + Session[ApplicationConstants.LOGIN_NAME.ToString()];

                    firstLevelNode.ChildNodes.Add(secondLevelNode);
                    currentNode = secondLevelNode;
                    Session[ApplicationConstants.CURRENT_NODE.ToString()] = currentNode;
                    return firstLevelNode;
                }

                try
                {
                    secondLevelNode.Text = new HierarchyDatasetTableAdapters.GetEmpByRoleTableAdapter().GetEmpByRoleOfJuniorForAreaMgr(Session[ApplicationConstants.LOGIN_NAME.ToString()].ToString(), HierarchyDSD.treeSequence[0][1], Double.Parse(Session[ApplicationConstants.CHOOSEN_YEAR.ToString()].ToString()), Double.Parse(Session[ApplicationConstants.CHOOSEN_MONTH.ToString()].ToString())).Rows[0][0].ToString();
                    secondLevelNode.Value = ApplicationStrings.EMP_NAME_PREFIX + secondLevelNode.Text + Roles.PROHIBITED;
                }
                catch (Exception)
                {
                   return new TreeNode("No Data Available", Roles.PROHIBITED.ToString());
                }

                firstLevelNode.ChildNodes.Add(secondLevelNode);



                // Adding Organization Name (child of Organization Parent Name)
                TreeNode thirdLevelNode = new TreeNode();
                TreeNode fouthLevelNode = new TreeNode();

                // Session[ApplicationConstants.ORGANIZATION_NAME.ToString()] = areaNBrachDt.Rows[0][HierarchyDSD.treeSequence[1][0]].ToString();

                valuePrefix = areaNBrachDt.Rows[0][HierarchyDSD.treeSequence[1][0]].ToString() + "@@" + valuePrefix;

                thirdLevelNode.Text = areaNBrachDt.Rows[0][HierarchyDSD.treeSequence[1][0]].ToString();// +"_BM"; ;
                thirdLevelNode.Value = valuePrefix + ApplicationStrings.ROLE_PREFIX + Roles.BM.ToString() + Roles.PROHIBITED;

                if (currentRole.Trim().Equals(HierarchyDSD.treeSequence[1][1]))
                {
                    thirdLevelNode.Text = areaNBrachDt.Rows[0][HierarchyDSD.treeSequence[1][0]].ToString();// +"_" + currentRole;
                    thirdLevelNode.Value = valuePrefix + ApplicationStrings.ROLE_PREFIX + currentRole;

                    fouthLevelNode.Text = Session[ApplicationConstants.LOGIN_NAME.ToString()].ToString();
                    fouthLevelNode.Value = valuePrefix + ApplicationStrings.EMP_NAME_PREFIX + Session[ApplicationConstants.LOGIN_NAME.ToString()];

                    secondLevelNode.ChildNodes.Add(thirdLevelNode);
                    thirdLevelNode.ChildNodes.Add(fouthLevelNode);
                    currentNode = fouthLevelNode;
                    Session[ApplicationConstants.CURRENT_NODE.ToString()] = currentNode;
                    return firstLevelNode;
                }


                fouthLevelNode.Text = new HierarchyDatasetTableAdapters.GetEmpByRoleTableAdapter().GetEmpByRoleOfJuniorForBM(Session[ApplicationConstants.LOGIN_NAME.ToString()].ToString(), HierarchyDSD.treeSequence[1][1], Double.Parse(Session[ApplicationConstants.CHOOSEN_YEAR.ToString()].ToString()), Double.Parse(Session[ApplicationConstants.CHOOSEN_MONTH.ToString()].ToString())).Rows[0][0].ToString();
                fouthLevelNode.Value = valuePrefix + ApplicationStrings.EMP_NAME_PREFIX + secondLevelNode.Text + Roles.PROHIBITED;

                secondLevelNode.ChildNodes.Add(thirdLevelNode);
                thirdLevelNode.ChildNodes.Add(fouthLevelNode);


                // Adding Roles within Branch Manager
                TreeNode fiftLevelNode = new TreeNode();
                TreeNode sixthLevelNode = new TreeNode();

                //if ("RO".Equals(currentRole.Trim()) || "SO".Equals(currentRole.Trim()) || "PBO".Equals(currentRole.Trim()))
                for (int i = 0; i < HierarchyDSD.dsdHierarchy[Roles.BM.ToString()].Length; i++)
                {
                    if (!HierarchyDSD.dsdHierarchy[Roles.BM.ToString()][i].Equals(currentRole.Trim()))
                    {
                        continue;
                    }

                    fiftLevelNode.Text = currentRole;
                    fiftLevelNode.Value = valuePrefix + ApplicationStrings.ROLE_PREFIX + fiftLevelNode.Text + Roles.PROHIBITED;

                    sixthLevelNode.Text = Session[ApplicationConstants.LOGIN_NAME.ToString()].ToString();
                    sixthLevelNode.Value = valuePrefix + ApplicationStrings.EMP_NAME_PREFIX + sixthLevelNode.Text;
                    sixthLevelNode.Select();

                    fouthLevelNode.ChildNodes.Add(fiftLevelNode);
                    fiftLevelNode.ChildNodes.Add(sixthLevelNode);

                    currentNode = sixthLevelNode;
                    Session[ApplicationConstants.CURRENT_NODE.ToString()] = currentNode;

                    Session[ApplicationConstants.IS_TILL_LAST_LEVEL.ToString()] = true;
                    break;
                }
           
            return firstLevelNode;
        }

        protected void hierarchyTreeView_SelectedNodeChanged(object sender, EventArgs e)
        {
            Session[KPIBalanceScoreCard.ApplicationConstants.ITEM_GROUPS.ToString()] = new KPIBalanceScoreCard.HierarchyDataset.ItemGroupsDataTable();
           // Session[ApplicationConstants.ITEM_DETAILS_MTD.ToString()] = new HierarchyDataset.ItemDetailsDataTable();
           // Session[ApplicationConstants.ITEM_DETAILS_YTD.ToString()] = new HierarchyDataset.ItemDetailsDataTable();

            if (hierarchyTreeView.SelectedNode == null ||  hierarchyTreeView.SelectedValue.Contains(Roles.PROHIBITED.ToString()))
            {
                return;
            }
            List<String> treeStructure = new List<string>();
            if (Session[ApplicationConstants.TREE_STRUCTURE.ToString()] != null)
            {
                treeStructure = (List<string>)Session[ApplicationConstants.TREE_STRUCTURE.ToString()];
            }

            if (true)
            {
                String valuePrefix = hierarchyTreeView.SelectedValue.Split(new String[] { "@@!!" }, StringSplitOptions.None)[0].Trim();

                valuePrefix = valuePrefix + "@@!!";

                String currentRole = Session[ApplicationConstants.CURRENT_ROLE.ToString()].ToString();
                String currentLogin = Session[ApplicationConstants.LOGIN_NAME.ToString()].ToString();

                if (hierarchyTreeView.SelectedNode.Value.Contains(ApplicationStrings.EMP_NAME_PREFIX) && Session[ApplicationConstants.IS_TILL_LAST_LEVEL.ToString()] == null)
                {
                    String selectedUser = hierarchyTreeView.SelectedValue.Split(new String[] { ApplicationStrings.EMP_NAME_PREFIX }, StringSplitOptions.None)[1].Trim();

                    HierarchyDataset.EmployeeRoleDataTable dt1 = new HierarchyDatasetTableAdapters.EmployeeRoleAdapter().GetEmployeeRoleByName(selectedUser, Double.Parse(Session[ApplicationConstants.CHOOSEN_YEAR.ToString()].ToString()), Double.Parse(Session[ApplicationConstants.CHOOSEN_MONTH.ToString()].ToString()));

                    String[] nextRoles = (HierarchyDSD.dsdHierarchy.ContainsKey(dt1.Rows[0][0].ToString().Trim()) ? HierarchyDSD.dsdHierarchy[dt1.Rows[0][0].ToString().Trim()] : new String[] { });

                    if (nextRoles == null || nextRoles.Length < 1)
                    {
                        //Session[ApplicationConstants.IS_TILL_LAST_LEVEL.ToString()] = true;
                    }

                    HierarchyDataset.GetBMForAreaMgrDataTable dt = new HierarchyDatasetTableAdapters.GetBMForAreaMgrTableAdapter().GetBMForAreaMgr(currentLogin, Double.Parse(Session[ApplicationConstants.CHOOSEN_YEAR.ToString()].ToString()), Double.Parse(Session[ApplicationConstants.CHOOSEN_MONTH.ToString()].ToString()));

                    foreach (String nextRole in nextRoles)
                    {
                        if (Roles.BM.ToString().Equals(nextRole))
                        {

                            TreeNode roleNode = new TreeNode();
                            TreeNode empNode = new TreeNode();

                            foreach (HierarchyDataset.GetBMForAreaMgrRow dr in dt)
                            {
                                roleNode = new TreeNode();
                                empNode = new TreeNode();
                                //Session[ApplicationConstants.ORGANIZATION_NAME.ToString()] = dr.OrganizationName;
                                roleNode.Text = dr.OrganizationName;// +"_" + Roles.BM.ToString();
                                roleNode.Value = dr.OrganizationName + "@@" + valuePrefix + ApplicationStrings.ROLE_PREFIX + Roles.BM.ToString();

                                empNode.Text = dr.EmployeeName;
                                empNode.Value = dr.OrganizationName + "@@" + valuePrefix + ApplicationStrings.EMP_NAME_PREFIX + dr.EmployeeName;

                                roleNode.ChildNodes.Add(empNode);
                                if (treeStructure.Contains<String>(roleNode.Value) || treeStructure.Contains<String>(empNode.Value))
                                {
                                    continue;
                                }
                                hierarchyTreeView.SelectedNode.ChildNodes.Add(roleNode);
                                treeStructure.Add(roleNode.Value);
                                treeStructure.Add(empNode.Value);
                            }
                        }
                        else
                        {
                            HierarchyDataset.EmpListDataTable empDt = new HierarchyDatasetTableAdapters.EmpListTableAdapter().GetEmpList(nextRole, selectedUser, Double.Parse(Session[ApplicationConstants.CHOOSEN_YEAR.ToString()].ToString()), Double.Parse(Session[ApplicationConstants.CHOOSEN_MONTH.ToString()].ToString()));

                            TreeNode roleNode = new TreeNode();
                            TreeNode empNode = new TreeNode();

                            roleNode.Text = nextRole;
                            roleNode.Value = valuePrefix + ApplicationStrings.ROLE_PREFIX + nextRole;


                            foreach (HierarchyDataset.EmpListRow dr in empDt)
                            {
                                empNode = new TreeNode();

                                empNode.Text = dr.EmployeeName;
                                empNode.Value = valuePrefix + ApplicationStrings.EMP_NAME_PREFIX + dr.EmployeeName;

                                roleNode.ChildNodes.Add(empNode);
                            }

                            if (treeStructure.Contains<String>(roleNode.Value) || treeStructure.Contains<String>(empNode.Value))
                            {
                                continue;
                            }

                            hierarchyTreeView.SelectedNode.ChildNodes.Add(roleNode);
                            treeStructure.Add(roleNode.Value);
                            treeStructure.Add(empNode.Value);
                        }
                    }
                }
                else
                {
                    //message = "Not Equal";
                }

                Session[ApplicationConstants.TREE_STRUCTURE.ToString()] = treeStructure;
                
            }
            try
            {
                if (hierarchyTreeView.SelectedValue.Contains("@@"))
                {
                    Session[ApplicationConstants.ORGANIZATION_NAME.ToString()] = hierarchyTreeView.SelectedValue.Split(new String[] { "@@!!" }, StringSplitOptions.None)[0].Trim().Split(new String[] { "@@" }, StringSplitOptions.None)[0];
                }
            }
            catch { }

            HierarchyDataset.ItemGroupsDataTable itemGroupDt = new HierarchyDataset.ItemGroupsDataTable();

            if (hierarchyTreeView.SelectedValue != null && hierarchyTreeView.SelectedValue.Contains(ApplicationStrings.ROLE_PREFIX))
            {
                String role = hierarchyTreeView.SelectedValue.Split(new String[] { ApplicationStrings.ROLE_PREFIX }, StringSplitOptions.None)[1].Trim();

                Session[ApplicationConstants.SELECTED_ROLE.ToString()] = role;
                Session[ApplicationConstants.SELECTED_EMPNAME.ToString()] = null;

                if (role.Equals(Roles.BM.ToString()))
                {
                    itemGroupDt = new HierarchyDatasetTableAdapters.ItemGroupsTableAdapter().GetItemGroupsForBM();
                    Session[ApplicationConstants.CHOOSEN_NODE_VALUE.ToString()] = "BM";
                }
                else
                {
                    itemGroupDt = new HierarchyDatasetTableAdapters.ItemGroupsTableAdapter().GetItemGroupByRole(role, Double.Parse(Session[ApplicationConstants.CHOOSEN_YEAR.ToString()].ToString()), Double.Parse(Session[ApplicationConstants.CHOOSEN_MONTH.ToString()].ToString()));
                    Session[ApplicationConstants.CHOOSEN_NODE_VALUE.ToString()] = role;
                }
            }
            else if (hierarchyTreeView.SelectedValue != null && hierarchyTreeView.SelectedValue.Contains(ApplicationStrings.EMP_NAME_PREFIX))
            {
                String empName = hierarchyTreeView.SelectedValue.Split(new String[] { ApplicationStrings.EMP_NAME_PREFIX }, StringSplitOptions.None)[1].Trim();

                Session[ApplicationConstants.SELECTED_ROLE.ToString()] = null;
                Session[ApplicationConstants.SELECTED_EMPNAME.ToString()] = empName;
                Session[ApplicationConstants.CHOOSEN_NODE_VALUE.ToString()] = empName;

                itemGroupDt = new HierarchyDatasetTableAdapters.ItemGroupsTableAdapter().GetItemGroupByEmpName(empName, Double.Parse(Session[ApplicationConstants.CHOOSEN_YEAR.ToString()].ToString()), Double.Parse(Session[ApplicationConstants.CHOOSEN_MONTH.ToString()].ToString()));
            }

            Session[ApplicationConstants.ITEM_GROUPS.ToString()] = itemGroupDt;

            //Session[ApplicationConstants.ITEM_DETAILS_MTD.ToString()] = new HierarchyDataset.ItemDetailsDataTable();
           // Session[ApplicationConstants.ITEM_DETAILS_YTD.ToString()] = new HierarchyDataset.ItemDetailsDataTable();
           // Session[KPIBalanceScoreCard.ApplicationConstants.SELECTED_ITEM_GROUP.ToString()] = "";

        }

        protected void refreshTree_Click(object sender, EventArgs e)
        {
            Session[ApplicationConstants.TREE_STRUCTURE.ToString()] = null;
            hierarchyTreeView.Nodes.Clear();
            
            bool isAdmin = Boolean.Parse(Session[ApplicationConstants.IS_ADMIN.ToString()] == null ? "false" : Session[ApplicationConstants.IS_ADMIN.ToString()].ToString());
            if (isAdmin)
            {
                HierarchyDataset.AdminDataTable adt = (HierarchyDataset.AdminDataTable)new HierarchyDatasetTableAdapters.AdminTableAdapter().GetData();
                foreach (HierarchyDataset.AdminRow row in adt.Rows)
                {
                    TreeNode tn = initializeTree(row.EmployeeUserRef);

                    if (!tn.Value.Equals(Roles.PROHIBITED.ToString()))
                    {
                        hierarchyTreeView.Nodes.Add(tn);
                    }
                }

            }
            else
            {
                hierarchyTreeView.Nodes.Add(initializeTree(Session[ApplicationConstants.LOGIN_PK.ToString()].ToString()));
            }

            hierarchyTreeView.ExpandAll();

            Session[KPIBalanceScoreCard.ApplicationConstants.ITEM_GROUPS.ToString()] = new KPIBalanceScoreCard.HierarchyDataset.ItemGroupsDataTable();
           // Session[ApplicationConstants.ITEM_DETAILS_MTD.ToString()] = new HierarchyDataset.ItemDetailsDataTable();
          //  Session[ApplicationConstants.ITEM_DETAILS_YTD.ToString()] = new HierarchyDataset.ItemDetailsDataTable();

        }
    }
}
